#include "Thread.h"

#include <iostream>

using namespace std;

Thread::Thread(){
    _t_obj=NULL;
    _running = false;
    _terminate = false;
}

void Thread::start(void* param){

    if(_running){
        cerr << "Thread is already running" << endl;
        return;
    }
    //create parameter to pass thread function.

    _t_obj = new Thread_Obj;
    _t_obj->thr=this;
    _t_obj->param=param;

    //create thread
    pthread_create(&_thread_id, NULL, &thread_function, _t_obj);
    _running = true;
}

void* Thread::end(){
    void* r_value;
    _terminate = true; //indicate to terminate as soon as possible
    return join();
}

void* Thread::thread_function(void * param){
    Thread_Obj* t_obj = (Thread_Obj*)param;
    return t_obj->thr->run(t_obj->param);
}

void* Thread::join(){
    void* r_value;
    pthread_join(_thread_id,&r_value);
    return r_value;
}
